package com.javatian.controller;

import com.github.pagehelper.PageInfo;
import com.javatian.common.Result;
import com.javatian.entity.Account;
import com.javatian.entity.CommentInfo;
import com.javatian.service.CommentInfoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 商品评价信息控制器
 */
@RestController
@RequestMapping(value = "/commentInfo")
public class CommentInfoController {

    //用户信息
    @Value("${const.user}")
    private String user;

    @Resource
    private CommentInfoService commentInfoService;


    /**
     * 新增一个商品评价信息
     */
    @PostMapping
    public Result<CommentInfo> add(@RequestBody CommentInfo commentInfo,HttpServletRequest request){
        Account account = (Account) request.getSession().getAttribute(user);
        commentInfo.setUserId(account.getId());
        return Result.success( commentInfoService.add(commentInfo));
    }

    /**
     * 根据主键id删除一个商品评价信息
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Long id){
        commentInfoService.delete(id);
        return Result.success();
    }

    /**
     * 修改一个商品评价信息
     */
    @PutMapping
    public Result update(@RequestBody CommentInfo commentInfo){
        commentInfoService.update(commentInfo);
        return Result.success();
    }

    /**
     * 根据主键id获取一个商品评价信息对象
     */
    @GetMapping("/{id}")
    public Result<CommentInfo> detail(@PathVariable Long id){
        CommentInfo commentInfo = commentInfoService.findById(id);
        return Result.success(commentInfo);
    }

    /**
     * 查询所有商品评价信息记录
     */
    @GetMapping
    public Result<List<CommentInfo>> all(){
        return Result.success(commentInfoService.findAll());
    }


    /**
     * 查询某个商品的评价信息
     */
    @GetMapping("/all/{goodsId}")
    public Result<List<CommentInfo>> all(@PathVariable("goodsId") Long goodsId){
        return Result.success(commentInfoService.findAll(goodsId));
    }

    /**
     * 根据条件分页查询
     * @param pageNum 第几页
     * @param pageSize 每页数量
     * @return 当前页的List列表
     */
    @GetMapping("/page/{name}")
    public Result<PageInfo<CommentInfo>> page(@RequestParam(required = false,defaultValue = "1") Integer pageNum,
                                            @RequestParam(required = false,defaultValue = "5") Integer pageSize,
                                            @PathVariable String name,
                                            HttpServletRequest request){
        Account account =(Account) request.getSession().getAttribute(user);
        return Result.success(commentInfoService.findPage(pageNum,pageSize,name,account));
    }

}
